package com.zhouzi.zhaoyang.ui.activity

import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.widget.Toast
import com.google.zxing.integration.android.IntentIntegrator
import com.tencent.wxpayface.IWxPayfaceCallback
import com.tencent.wxpayface.WxPayFace
import com.zhouzi.zhaoyang.R
import com.zhouzi.zhaoyang.base.App
import com.zhouzi.zhaoyang.base.BaseActivity
import com.zhouzi.zhaoyang.config.JobFinal
import com.zhouzi.zhaoyang.mvp.p.ReturnCashActivityPresenter
import com.zhouzi.zhaoyang.mvp.v.IReturnCashActivityView
import com.zhouzi.zhaoyang.service.VoiceService
import com.zhouzi.zhaoyang.util.Calculator
import kotlinx.android.synthetic.main.return_cash_activity.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class ReturnCashActivity : BaseActivity(), IReturnCashActivityView {
    override fun errorToken() {
        exitToLogin()
    }
    private val p = ReturnCashActivityPresenter()

    init {
        p.attachView(this)
    }


    override fun onStop() {
        super.onStop()
        WxPayFace.getInstance().stopCodeScanner()
        if (serviceIntent != null){
            stopService(serviceIntent)
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        p.detachView()

    }

    override fun showLoadDialog() {
        loadDialog.show()

    }

    override fun dismissLoadDialog() {
        loadDialog.dismiss()

    }

    private var job: Job? = null

    private fun countDown() {
        /*开始倒计时30s退出页面*/
        job = GlobalScope.launch {
            delay(JobFinal.EXECUTE_TIME)
            val intent = Intent(mContext, VoiceService::class.java)
            intent.putExtra("voiceStr", "交易失败")
            startService(intent)
            var activity = Intent(mContext,MainActivity :: class.java)
            startActivity(activity)
            finish()
        }
    }

    override fun returnDepositFailed(msg: String?) {

        val intent = Intent(mContext, VoiceService::class.java)
        intent.putExtra("voiceStr", msg)
        startService(intent)

//        var returnMain = Intent(this, MainActivity::class.java)
//        startActivity(returnMain)

    }


    override fun returnDepositSuccess() {
        val intent = Intent(mContext, VoiceService::class.java)
        intent.putExtra("voiceStr", "退款成功")
        startService(intent)
        finish()


        var returnMain = Intent(this, MainActivity::class.java)
        startActivity(returnMain)

    }


    var enter = 160
    var count = 1
    var moneyFee = "0"
    var goodsNo = "0"
    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {


        Calculator.onKeyEvent(
            when (event?.keyCode) {
                KeyEvent.KEYCODE_NUMPAD_1 -> Calculator.KeyCode._1
                KeyEvent.KEYCODE_NUMPAD_2 -> Calculator.KeyCode._2
                KeyEvent.KEYCODE_NUMPAD_3 -> Calculator.KeyCode._3
                KeyEvent.KEYCODE_NUMPAD_4 -> Calculator.KeyCode._4
                KeyEvent.KEYCODE_NUMPAD_5 -> Calculator.KeyCode._5
                KeyEvent.KEYCODE_NUMPAD_6 -> Calculator.KeyCode._6
                KeyEvent.KEYCODE_NUMPAD_7 -> Calculator.KeyCode._7
                KeyEvent.KEYCODE_NUMPAD_8 -> Calculator.KeyCode._8
                KeyEvent.KEYCODE_NUMPAD_9 -> Calculator.KeyCode._9
                KeyEvent.KEYCODE_NUMPAD_0 -> Calculator.KeyCode._0
                KeyEvent.KEYCODE_NUMPAD_DOT -> Calculator.KeyCode._D
                KeyEvent.KEYCODE_DEL -> Calculator.KeyCode._B
                KeyEvent.KEYCODE_ENTER -> Calculator.KeyCode._E
                else -> return super.onKeyDown(event!!.keyCode, event)
            }
        )


        if ((event?.keyCode == KeyEvent.KEYCODE_ENTER || event?.keyCode == enter) && event.getAction() != KeyEvent.ACTION_UP) {


            if (TextUtils.isEmpty(tvMoneyFee.text.toString())) {
                moneyFee = "0"
            } else {
                moneyFee = tvMoneyFee.text.toString()

            }



            if (count == 1) {

                tvSure.requestFocus()


                serviceIntent.putExtra("voiceStr", "消费金额" + moneyFee + "元")
                startService(serviceIntent)

                if (TextUtils.isEmpty(etCommercialNO.text.toString())){
                    wxScan()
//                    scan(this)
                }else{
                    val fen = Calculator.yuan2Fen(moneyFee)
                    goodsNo = etCommercialNO.text.toString()
                    Log.e("goodsNo1", goodsNo)
                    var map = mutableMapOf<String, String>(
                        Pair("consumeFee", fen.toString()),
                        Pair("outTradeNo", goodsNo),
                        Pair("deviceNo", Build.SERIAL)

                    )
                    p.returnDeposit(map)
                    etCommercialNO.setText("")
                }

                return false
            }
            count++

        }




        return super.dispatchKeyEvent(event)

    }


    public fun scan(activity: BaseActivity) {

        val intent = Intent(App.mContext, VoiceService::class.java)
        intent.putExtra("voiceStr", "请对准二维码")
        startService(intent)





        IntentIntegrator(activity)
            .setCaptureActivity(MyScanActivity().javaClass)
            .setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)// 扫码的类型,可选：一维码，二维码，一/二维码
            .setPrompt("请对准二维码")// 设置提示语
            .setCameraId(0)// 选择摄像头,可使用前置或者后置
            .setBeepEnabled(false)// 是否开启声音,扫完码之后会"哔"的一声
            .setBarcodeImageEnabled(true)// 扫完码之后生成二维码的图片
            .initiateScan()// 初始化扫码

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        var result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)


        if (result != null) {

            etCommercialNO.setText(result.contents)

            if (result.getContents() == null) {
                val intent = Intent(mContext, VoiceService::class.java)
                serviceIntent.putExtra("voiceStr", "扫码失败")
                startService(intent)
            } else {
                val intent = Intent(mContext, VoiceService::class.java)
                intent.putExtra("voiceStr", "扫码成功")
                startService(intent)
                goodsNo = result.contents
                val fen = Calculator.yuan2Fen(moneyFee)
                var map = mutableMapOf<String, String>(
                    Pair("consumeFee", fen.toString()),
                    Pair("outTradeNo", goodsNo),
                    Pair("deviceNo", Build.SERIAL)

                )
                p.returnDeposit(map)
                etCommercialNO.setText("")
            }
            super.onActivityResult(requestCode, resultCode, data)
        }

    }

    private fun wxScan() {

        stopService(serviceIntent)
        var intent = Intent(mContext,VoiceService::class.java)
        intent.putExtra("voiceStr", "请对准上方摄像头扫码")
        startService(intent)

        WxPayFace.getInstance().startCodeScanner( object  : IWxPayfaceCallback(){


            override fun response(info: MutableMap<Any?, Any?>?) {


                Log.e("startCodeScanner",info.toString())

                if (info != null){
                    var return_code = info.get("return_code")
                    var return_msg = info.get("return_msg")
                    var code_msg = info.get("code_msg")
                    var  resultString = "startCodeScanner, return_code : " + return_code + " return_msg : " + return_msg + " code_msg: " + code_msg

                   if (code_msg != null){

                       goodsNo = code_msg.toString()
                       WxPayFace.getInstance().stopCodeScanner()


                       Handler(Looper.getMainLooper()).post {

                           etCommercialNO.setText(code_msg.toString())


                           val fen = Calculator.yuan2Fen(moneyFee)
                           var map = mutableMapOf<String, String>(
                               Pair("consumeFee", fen.toString()),
                               Pair("outTradeNo", goodsNo),
                               Pair("deviceNo", Build.SERIAL)

                           )
                           p.returnDeposit(map)
                       }




                   }else{
                       Toast.makeText(mContext,"请重新扫码",Toast.LENGTH_SHORT).show()
                       val intent = Intent(App.mContext, VoiceService::class.java)
                       intent.putExtra("voiceStr", "请重新扫码")
                       startService(intent)
                   }


                }

            }
        })


    }


    override fun getLayoutId(): Int {
        return R.layout.return_cash_activity
    }


    var  serviceIntent = Intent()
    override fun initView() {

        /*初始化刷脸*/
        WxPayFace.getInstance().initWxpayface(mContext, object : IWxPayfaceCallback() {
            override fun response(p0: MutableMap<Any?, Any?>?) {
                Handler(Looper.getMainLooper()).post {
                    if (isSuccessInfo(p0)) {

                    } else {
                        Toast.makeText(mContext, "初始化失败，请稍后再试", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        })

          serviceIntent = Intent(mContext,VoiceService::class.java)


        viewClick()

    }

    private fun viewClick() {

    }

    /*判断回调是否异常*/
    private fun isSuccessInfo(info: Map<*, *>?): Boolean {


        if (info == null) {
            RuntimeException("调用返回为空").printStackTrace()
            return false
        }
        val code = info["return_code"] as String
        val msg = info["return_msg"] as String
        Log.d("response parameter", "response | getWxpayfaceRawdata $code | $msg")
        if (code == null || info.get("rawdata").toString() == null || !code.equals("SUCCESS")) {
            RuntimeException("调用返回非成功信息,return_msg:" + msg + "   ").printStackTrace()
            return false
        }
        return true
    }

    override fun onStart() {
        super.onStart()

        serviceIntent.putExtra("voiceStr", "请输入消费金额")
        startService(serviceIntent)

        tvMoneyFee.requestFocus()




        tvApBtnBack.setOnClickListener {

            var intent = Intent(this, MainActivity::class.java)
            startActivity(intent)

            finish()

            Calculator.reset()


        }


    }




    override fun onResume() {
        super.onResume()
        countDown()

    }

    override fun onPause() {
        super.onPause()
      job?.cancel()
    }

}
